package com.google.code.chaotic.server;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import com.google.code.chaotic.dto.UserType;
import com.google.code.chaotic.model.Commuter;
import com.google.code.chaotic.model.User;
import com.google.code.chaotic.shared.AuthException;
import com.google.code.chaotic.shared.NotAuthorizedException;
import com.google.code.chaotic.shared.NotLoggedInException;

public class ServerSessionManager {

	private static Logger logger = Logger.getLogger( //
			ServerSessionManager.class.getName());
	//

	private static ServerSessionManager instance;

	private ServerSessionManager() {
	}

	public static synchronized ServerSessionManager getInstance() {
		if (instance == null)
			instance = new ServerSessionManager();
		return instance;
	}

	//

	// TODO: Sessions must be stored in the datastore instead!
	private Map<String, User> sessionMap = Collections
			.synchronizedMap(new HashMap<String, User>());

	//

	public synchronized void addSession(String sessionId, User user) {
		sessionMap.put(sessionId, user);
		logger.info("@@@@@ Session STARTED: " + sessionId //
				+ ", username: " + user.getUsername());
	}

	public User removeSession(String sessionId) {
		User user = sessionMap.remove(sessionId);
		logger.info("@@@@@ Session   ENDED: " + sessionId //
				+ ", username: " + user.getUsername());
		return user;
	}

	public static void assertRole(String sessionId, UserType role)
			throws AuthException {

		User user = null;
		if (sessionId == null
				|| (user = getInstance().sessionMap.get(sessionId)) == null)
			throw new NotLoggedInException();

		switch (user.getUserType()) {
		case ADMIN:
			// Allow every thing!
			break;
		case COMMUTER:
			if (role != UserType.COMMUTER)
				throw new NotAuthorizedException();
			break;
		}
	}

	public User getUser(String sessionId) {
		return getInstance().sessionMap.get(sessionId);
	}
}
